package net.cyue.android

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.KeyEvent
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.Toast
import androidx.activity.ComponentActivity
import com.fasterxml.jackson.databind.ObjectMapper
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.normal.TedPermission
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.kongzue.dialogx.style.MaterialStyle
import com.wragony.android.jsbridge.JsBridge
import net.cyue.android.js.AndroidJSInterface
import net.cyue.android.js.DialogXJSInterface
import net.cyue.android.js.module.DialogXJSModule
import net.cyue.android.js.module.HTTPJSModule
import net.cyue.android.js.module.UtilJSModule
import okhttp3.Call
import okhttp3.Response
import java.io.File
import java.io.IOException

class MainActivity : ComponentActivity() {

    private val jsBridge: JsBridge;
    private lateinit var webView: WebView;

    init {
        // JSBridge
        this.jsBridge = JsBridge.loadModule(
            UtilJSModule(this),
            DialogXJSModule(),
            HTTPJSModule()
        );
    }

    // openAlbum
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            Util.callAlbumCallback(null)
            return
        }
        val fullPhotoUri = data.data
        Util.callAlbumCallback(fullPhotoUri)
    }


    override fun onBackPressed() {
        super.onBackPressed()
        this.webView.goBack();
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean
    {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.webView.goBack();
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val permissionListener: PermissionListener = object : PermissionListener {
            override fun onPermissionGranted() {
                // Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
            }

            override fun onPermissionDenied(deniedPermissions: List<String>) {
                // Toast.makeText(MainActivity.this, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (!Environment.isExternalStorageManager()) {
                        val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                        this@MainActivity.startActivity(intent);
                    }
                }
            }
        }
        // 请求应用权限
        TedPermission
            .create()
            .setPermissionListener(permissionListener)
            .setPermissions(
                Manifest.permission_group.STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            .check();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        {
            TedPermission
                .create()
                .setPermissionListener(permissionListener)
                .setPermissions(
                    Manifest.permission_group.NOTIFICATIONS,
                    Manifest.permission.POST_NOTIFICATIONS,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_AUDIO
                )
                .check();
        }


        // 配置 DialogX
        DialogX.init(this);
        DialogX.globalStyle = MaterialStyle.style();

        // set content view
        setContentView(R.layout.activity_main);

        // web-view
        this.webView = this.findViewById(R.id.webview);

        // JSBridge Settings
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webView.webChromeClient = MyWebChromeClient(jsBridge);
        }
        webView.setWebViewClient(MyWebViewClientCompat(jsBridge));


        // web-view setting
        val webViewSettings = webView.settings;
        webViewSettings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE;
        webViewSettings.javaScriptEnabled = true;
        webViewSettings.javaScriptCanOpenWindowsAutomatically = true;
        webViewSettings.domStorageEnabled = true;

        // JS interface
        webView.addJavascriptInterface(AndroidJSInterface(this), "Android");
        webView.addJavascriptInterface(DialogXJSInterface(), "DialogX");

        webView.loadUrl("https://cyue.net");

        val that = this;
        val packageInfo = this.packageManager.getPackageInfo(this.packageName, 0);
        val currentVersion = packageInfo.versionName;

        try {
            Util.httpGet(
                "https://cyue.net/api/android/version",
                null,
                null,
                object : okhttp3.Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        PopTip.show(e.message);
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val jsonString = response.body?.string();
                        val objectMapper = ObjectMapper();
                        val nodeTree = objectMapper.readTree(jsonString).get("data");
                        val newestVersion = nodeTree.get("newestVersion").textValue();
                        if (currentVersion != newestVersion)
                        {
                            val newestVersionCode = nodeTree.get("version").get(newestVersion).textValue();
                            val downloadURL = "http://android.cyue.net/$newestVersionCode.apk";
                            val fileName = "尘跃的个人分享网-$newestVersion.apk";
                            MessageDialog.build()
                                .setOkButton("下载")
                                .setCancelButton("取消")
                                .setTitle("更新")
                                .setMessage("是否下载最新版本？")
                                .show()
                                .setOkButton { _, _ ->
                                    Util.downloadFile(
                                        that,
                                        downloadURL,
                                        fileName
                                    ) {
                                        TipDialog.show(
                                            "下载完成",
                                            WaitDialog.TYPE.SUCCESS
                                        );
                                    };
                                    false;
                                }

                        }
                        else {
                            that.runOnUiThread {
                                Toast
                                    .makeText(that, "当前已是最新版本", Toast.LENGTH_SHORT)
                                    .show();
                            };
                        }
                    }
                }
            );
        } catch (e: IOException) {
            Toast
                .makeText(this, e.message, Toast.LENGTH_SHORT)
                .show();
        }

    }

    override fun onDestroy() {
        this.jsBridge.release();
        super.onDestroy();
    }
}



